<?php

namespace App\Http\Controllers;

use App\Models\Org;
use App\Models\Project;
use App\Models\ProjectHire;
use App\Models\RewardHistory;
use App\Models\WechatTempMsg;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ProjectRewardController extends Controller
{
    public function index(Request $request, $project_id) {
        Project::findOrFail($project_id);


        $perPage = $request->get('perPage', 10);
        $query = ProjectHire::with(['project', 'user.volunteer'])->where('project_id', '=', $project_id);

        $query->where('verify_status', '=', 1);

        $info = $query->paginate($perPage)->toArray();

        $user_ids = array_map(function($item) {
            return $item['user_id'];
        }, $info['data']);

        $rewards = DB::table('user_clock_in')
            ->where('project_id', '=', $project_id)
            ->select(DB::raw('sum(reward_time) as clock_time_count, user_id'))
            ->whereIn('user_id', $user_ids)
            ->groupBy('user_id')
            ->get();

        $rewardMap = [];
        foreach ($rewards as $reward) {
            $rewardMap[$reward->user_id] = $reward;
        }

        foreach ($info['data'] as &$item) {
            if (isset($rewardMap[$item['user_id']])) {
                $item['clock_time_count'] = $rewardMap[$item['user_id']]->clock_time_count;
            } else {
                $item['clock_time_count'] = 0;
            }

            $item['append_reward_time_count'] = $item['reward_time'] - $item['clock_time_count'];
        }

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function append(Request $request, $project_id, $id) {
        $projectInfo = Project::findOrFail($project_id);
        $orgInfo = Org::find($projectInfo->org_id);
        $scoreConf = $orgInfo->getScoreConf();

        $this->validate($request, [
            'plus' => 'required'
        ]);

        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        foreach ($ids as $id) {
            $reward = ProjectHire::findOrFail($id);
            $history = new RewardHistory();
            $history->fill([
                'user_id' => $reward->user_id,
                'project_id' => $project_id,
                'reward_time' => $request->get('plus'),
                'desc' => '手动录入'
            ]);
            $history->save();

            //微信模版消息，后台补录时长
            WechatTempMsg::add(6, ['reward_time_history_id'=>$history->id]);

            $time = floatval($request->get('plus'));
            $reward->plusTime($time);
            // $reward->project->plusTime($time);
            $reward->project->team->plusTime($time);
            $reward->volunteer->plusTime($time);

            $addScore = $time * $scoreConf['reward_time'];
            $reward->volunteer->increment('score', $addScore);
            DB::table('user_score_item')->insert(['user_id'=>$reward->user_id, 'type'=>0, 'score'=>$addScore, 'remark'=>'参加志愿活动']);
            Log::info('SCORE 补录时长奖励积分 userId:'.$reward->user_id.'  score:'.$addScore);
        }

        return $this->returnJSON(null, 0, "添加成功");
    }
}
